import 'package:flutter/services.dart';

class FeedLengthLimitingFormatter extends LengthLimitingTextInputFormatter {
  FeedLengthLimitingFormatter(int maxLength) : super(maxLength);

  @override
  TextEditingValue formatEditUpdate(
      TextEditingValue oldValue, TextEditingValue newValue) {
    int oldLength = oldValue.text.length;
    int newLength = newValue.text.length;

    ///1、当第一次输入｜输入长度未达到限制长度｜删除内容时 不需要进行处理
    if (oldLength == 0 ||
        newLength <= (maxLength ?? 120) ||
        oldLength > newLength) {
      return super.formatEditUpdate(oldValue, newValue);
    }

    ///2、获取到当前输入了哪些内容
    var inputStr = newValue.text.substring(
        oldValue.selection.baseOffset, newValue.selection.baseOffset);

    ///3、根据限制的长度截取输入的内容
    var cutStr = inputStr.substring(0, (maxLength ?? 120) - oldLength);

    ///4、在光标位置插入截取的内容
    return oldValue.replaced(
      TextRange(
          start: oldValue.selection.baseOffset,
          end: oldValue.selection.baseOffset),
      cutStr,
    );
  }
}
